<template>
  <n-modal v-model:show="showModal" preset="dialog" :show-icon="false">
    <n-card v-if="editType==='edit' || editType==='add'">
      <h1 class="text-center text-4xl mb-4">{{ title }}</h1>
      <flexform ref="flexFormref" :formList="formList" :formValue="formValue">
        <template #cascader="{formitem}">
          <n-form-item :path="formitem.path || formitem.key" :label="formitem.label + '：'"
                       :type="formitem.datetype || 'date'" :rule="formitem.rules||[]">
            <n-cascader
                v-model:value="formValue['parent']"
                :placeholder="formitem.placeholder || '请选择'"
                :options="parentOptions"
                remote
                :show-path="false"
                clearable
                :on-load="handleLoad"
            />
          </n-form-item>
        </template>
      </flexform>
      <template #action>
        <div class="w-full h-10 flex justify-end items-center">
          <n-button @click="doClose">取消</n-button>
          <n-button @click="handleOK" type="primary">{{ formValue.id ? "编辑" : "创建" }}</n-button>
        </div>
      </template>
    </n-card>
    <n-card v-if="editType==='view'">
      <h1 class="text-center text-4xl mb-4">{{ title }}</h1>
      <descriptions :infoList="_lanmulist"></descriptions>
      <template #action>
        <div class="w-full h-10 flex justify-end items-center">
          <n-button @click="clickEdit" type="primary">编辑</n-button>
          <n-button @click="doClose">关闭</n-button>
        </div>
      </template>
    </n-card>
    <n-card v-if="editType==='success'">
      <n-result status="success" title="成功" :description="formValue.id?'编辑成功':'创建成功'">
      </n-result>
      <template #action>
        <div class="w-full h-10 flex justify-end items-center">
          <n-button @click="doClose">关闭</n-button>
        </div>
      </template>
    </n-card>
    <n-card v-if="editType==='error'">
      <n-result status="error" title="错误" >
        <template>
          <p>{{ errortext }}</p>
        </template>
      </n-result>
      <template #action>
        <div class="w-full h-10 flex justify-end items-center">
          <n-button @click="getreturn" type="primary">返回</n-button>
          <n-button @click="doClose">关闭</n-button>
        </div>
      </template>
    </n-card>
  </n-modal>
</template>

<script setup name="Edit">
import {useRoute, useRouter} from "vue-router";
import http from "@/request/request"
import guiling from "../../../../util/guiling";

const router = useRouter()
const route = useRoute()
const flexFormref = ref(null)   // 表单组件
const showModal = ref(false)    // 模态框的显示
const title = ref("")         // 标题
const loading = ref(false)    // 加载状态
const editType = ref("add")   // 类型，编辑。新建、查看
const formValue = ref({})   // 表单数据
const errortext = ref("")   // 错误信息
const emit = defineEmits(["shuaxin"])
// 弹窗初始化
const init = (type, item = null) => {
  editType.value = type
  switch (type) {
    case "add":
      title.value = "新建"
      break;
    case "edit":
      title.value = "编辑"
      break;
    case "view":
      title.value = "详情"
      break;
  }
  if (item) {
    formValue.value = item
  }
  getparentdata()
  showModal.value = true
}
// 弹窗关闭
const doClose = () => {
  showModal.value = false
  emit("shuaxin")
  reset()
}
// 弹窗初始化
const reset = () => {
  formValue.value = guiling(formValue.value)
  editType.value = ""
  title.value = ""
  parentOptions.value = []

}
// 点击确定
const handleOK = () => {
  if (formValue.value.id) {
    flexFormref.value.jiaoyan(updatefunc)
  } else {
    flexFormref.value.jiaoyan(createfunc)
  }
}

// 创建的处理函数
const createfunc = (data) => {
  http.zidianadd(data).then(res => {
    if (res && res.data.code === 0) {
      getsuccess()
    } else {
      getfaild()
    }
  }).catch(() => {
    getfaild()
  })
}
// 编辑的处理函数
const updatefunc = (data) => {
  http.zidianupdate(data, formValue.value.id).then(res => {
    if (res && res.data.code === 0) {
      getsuccess()
    } else {
      getfaild(res.data)
    }
  }).catch(() => {
    getfaild()
  })
}
// 字典的parent
const parentOptions = ref([])
// 表单配置
const formList = ref([
  {
    label: "参数名称",
    key: "name",
    type: "input",
    rules: [{required: true, message: "请输入参数名称", trigger: ["input", "change", "blur"]}, {
      max: 50,
      min: 2,
      message: "请输入2-50为的参数名称",
      trigger: ["input", "change", "blur"]
    },]
  },
  {
    label: "参数值",
    key: "value",
    type: "input",
    rules: [{required: true, message: "请输入参数值", trigger: ["input", "change", "blur"]}, {
      max: 50,
      min: 2,
      message: "请输入2-50为的参数值",
      trigger: ["input", "change", "blur"]
    },]
  },
  {
    label: "所属父级",
    key: "parent",
    type: "select",
    slot:"cascader",
    rules: [{required:true,message:"请选择所属父级", trigger: ["input", "change", "blur"]}],
  },
  {
    label: "描述",
    key: "desc",
    type: "textarea",
    rules: [{
      max: 2000,
      message: "请输入描述",
      trigger: ["input", "change", "blur"]
    },]
  },
])

// 交互成功
const getsuccess = () => {
  editType.value = "success"
  setTimeout(() => {
    doClose()
  }, 500)
}
// 交互失败
const getfaild = (jieguo) => {
  editType.value = "error"
  errortext.value = jieguo.toString()
}


// 显示相关的配置
const lanmulist = ref([
  {label: "参数名称", key: "name"},
  {label: "参数值", key: "value"},
  {label: "创建时间", key: "createdTime",render: (data)=>{
    return data ? new Date(data).toLocaleString("zh", {
      year: 'numeric',
      month: 'numeric',
      day: 'numeric',
      hour12: false,
      hour: 'numeric',
      minute: 'numeric',
      second: 'numeric'
    }) :""
    }},
  {label: "排序", key: "sort"},
  {label: "描述", key: "desc"},
])
const _lanmulist = computed(() => {
  return lanmulist.value.map(item => {
    return {...item, value: item.render?item.render(formValue.value[item.key]) : formValue.value[item.key]}
  })
})
// 点击编辑按钮
const clickEdit = () => {
  editType.value = "edit"
  title.value = "编辑"
}
// 点击返回
const getreturn = () => {
  if (formValue.value.id) {
    editType.value = "edit"
    title.value = "编辑"
  } else {
    editType.value = "add"
    title.value = "创建"
  }
  errortext.value = ""
}

// 获取字典
const handleLoad=(option)=>{
  return new Promise((resolve,reject) => {
    const config = {
      parent: option.key,
    }
    http.zidianfilter(config).then(res => {
      if (res.data.code === 0) {
        if (res.data.items.length === 0) {
          option.isLeaf = true
          console.log("处理完毕1",option)
        } else {
          option.children = res.data.items.map(item => {
            return {label: item.name, key: item.id,value:item.id, isLeaf: false,}
          })
          console.log("处理完毕2",option)
        }
        resolve()
        reject()
      }
    })
  })
}
// 获取第一层数据
const getparentdata=()=>{
  http.zidianfilter().then(res => {
    if(res.data.code===0){
      parentOptions.value = res.data.items.map(item=>{
        return {label: item.name, key: item.id, value: item.id,isLeaf:false}
      })
    }
  })
}
// 抛出属性和方法
defineExpose({init, doClose, reset})
// 初始化区域

</script>

<style scoped>

</style>
